package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.Expire;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.IExpireService;
import com.yh.correct.service.IJudicialDeptmentService;
import com.yh.correct.service.IStateChangeService;
/**
 * 矫正期满登记控制层
 * 
 * @author 王鹏程 
 * @Date 2017.03.15
 * @Time 13:25
 */
@RestController
@RequestMapping("/expire")
@PropertySource("classpath:config/system.properties")
public class ExpireController {
	/**
	 * 日志记录
	 */
	private static Logger logger = LogManager.getLogger(ExpireController.class);
	/**
	 * 文件保存路径
	 */
	@Value("${saveDir}")
	private String saveDir;
	/**
	 * 注入矫正期满登记服务层接口
	 */
	@Autowired
	private IExpireService expireService;
	/**
	 * 注入矫正状态变更记录服务层接口
	 */
	@Autowired
	private IStateChangeService stateChangeService;
	/**
	 * 注入司法所服务层接口
	 */
	@Autowired
	private IJudicialDeptmentService jud;
	/**
	 * 增加期满登记
	 * 
	 * @param moption
	 * @param ereport
	 * @param expire
	 * @param jdate
	 * @return
	 */
	@RequestMapping(value="/add")
	public ResultData addExpire(MultipartFile moption , MultipartFile ereport , @Valid Expire expire){ 
		String moptionName="期满合议表"+expire.getPid()+moption.getOriginalFilename().substring(moption.getOriginalFilename().lastIndexOf("."));
		String ereportName="期满鉴定表"+expire.getPid()+ereport.getOriginalFilename().substring(ereport.getOriginalFilename().lastIndexOf("."));
		expire.setMergeOption(moptionName);
		expire.setExpertiseReport(ereportName);
		try {
			moption.transferTo(new File(saveDir,moptionName));
			ereport.transferTo(new File(saveDir,ereportName));
		} catch (IllegalStateException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		int i = 0;
		try {
			i = expireService.addExpire(expire);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("增加成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("增加失败！");
		}
		logger.debug("增加期满登记!");
		return rd;
	}
	/**
	 * 期满登记首页跳转
	 * 
	 * @return
	 */
	@RequestMapping(value="/skip")
	public ModelAndView skip(){ 
		return new ModelAndView("end/expire");
	}
	/**
	 * 增加窗口跳转
	 * 
	 * @return
	 */
	@RequestMapping(value="/addSkip")
	public ModelAndView addSkip(){ 
		return new ModelAndView("end/expire_add");
	}
	/**
	 * 矫正所下拉框显示
	 *  
	 * @return
	 */
	@RequestMapping(value="/jselect")
	public List<Object> jShowSelect(){ 
		List<Object> list = jud.listJudicialDeptments();
		return list;
	}
	/**
	 * 第一次矫正人员下拉框显示
	 * 
	 * @return
	 */
	@RequestMapping(value="/pselect1")
	public List<CorrectedPerson> pShowSelecta(){
		CorrectedPerson correctedperson = new CorrectedPerson();
		correctedperson.setJid(1);
		List<CorrectedPerson> list = expireService.getPersonByJud(correctedperson);
		return list;
		
	}
	/**
	 * 矫正人员下拉框显示
	 * 
	 * @return
	 */
	@RequestMapping(value="/pselect")
	public List<CorrectedPerson> pShowSelect(Integer jid){
		CorrectedPerson correctedperson = new CorrectedPerson();
		correctedperson.setJid(jid);
		List<CorrectedPerson> list = expireService.getPersonByJud(correctedperson);
		return list;
		
	}
	/**
	 * 修改期满登记
	 * 
	 * @param expire
	 * @param jdate
	 * @param yoption
	 * @param yreport
	 * @param moption
	 * @param ereport
	 * @return
	 */
	@RequestMapping(value="/edit")
	public ResultData editExpire(@Valid Expire expire , String yoption ,String yreport ,MultipartFile moption , MultipartFile ereport){
		String moptionName = null;
		String ereportName = null;
		if(moption.isEmpty()){
			moptionName = yoption;
		}else{
			moptionName="期满合议表"+expire.getPid()+moption.getOriginalFilename().substring(moption.getOriginalFilename().lastIndexOf("."));
		}
		if(ereport.isEmpty()){
			ereportName = yreport;
		}else{
			ereportName="期满鉴定表"+expire.getPid()+ereport.getOriginalFilename().substring(ereport.getOriginalFilename().lastIndexOf("."));
		}
		expire.setMergeOption(moptionName);
		expire.setExpertiseReport(ereportName);
		try {
			moption.transferTo(new File(saveDir,moptionName));
			ereport.transferTo(new File(saveDir,ereportName));
		} catch (IllegalStateException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		int i = expireService.editExpire(expire);
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("修改成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("修改失败！");
		}
		logger.debug("修改期满登记!");
		return rd;
	}
	/**
	 * 删除期满登记
	 * 
	 * @param expire
	 * @return
	 */
	@RequestMapping(value="/del")
	public ResultData delExpire(Expire expire){ 
		int i = expireService.delExpire(expire);
		ResultData rd=new ResultData();
		if(i>0){
			rd.setCode(0);
			rd.setMessage("删除成功！");
		}else{
			rd.setCode(-1);
			rd.setMessage("删除失败！");
		}
		logger.debug("删除期满登记!");
		return rd;
	}
	/**
	 * 修改前查询单条详细期满登记
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/detail")
	public ModelAndView getaExpire(int id){ 
		logger.debug(id);
		Expire ex = new Expire();
		ex.setId(id);
		Map<String,Object> map = expireService.queryExpires(ex);
		logger.debug("修改前查询期满登记!");
		return new ModelAndView("end/expire_edit",map);
	}
	/**
	 * 查看单条详细期满登记
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/look")
	public ModelAndView getbExpire(int id){ 
		Expire ex = new Expire();
		ex.setId(id);
		Map<String,Object> map = expireService.queryExpires(ex);
		logger.debug("查询单条期满登记!");
		return new ModelAndView("end/expire_look",map);
	}
	/**
	 * 模糊查询期满登记
	 * 
	 * @param name
	 * @param jname
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@RequestMapping(value="/getLike")
	public ResultData getLikeExpires(@RequestParam("cname") String name,String jname,@RequestParam int pageSize,@RequestParam int pageNum){
		Map<String,Object> condition=new HashMap<String,Object>();
		condition.put("pageSize", pageSize);
		condition.put("pageNum", pageNum);
		condition.put("name", name);
		condition.put("jname", jname);
		Page page = expireService.queryLikeExpires(condition);
		ResultData rd=new ResultData();
		if(page!=null){
			List<Object> expire = new ArrayList<Object>();
			expire.add(page);
			rd.setCode(0);
			rd.setMessage("查询成功！");
			rd.setData(expire);
		}else{
			rd.setCode(-1);
			rd.setMessage("查询失败！");
		}
		logger.debug("查询期满登记!");
		return rd;
	}
	/**
	 * 期满登记合议表 鉴定表下载
	 * 
	 * @param filename
	 * @param hsr
	 * @return
	 */
	@RequestMapping(value="/fileDown")
	public ResultData fileDown(String filename,HttpServletResponse hsr){
		hsr.setContentType("application/octet-stream; charset=utf-8");		
		try {
			filename = new String(filename.getBytes("utf-8"), "ISO-8859-1");
		} catch (UnsupportedEncodingException e1) {			
			e1.printStackTrace();
		}		
		hsr.setHeader("Content-Disposition", "attachment; filename="+filename);		
		try {
			IOUtils.copy(new FileInputStream(new File(saveDir,filename)), hsr.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 导出Excle
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/excel")
	public String outExcle(HttpServletRequest request, HttpServletResponse response,@RequestParam("cname") String name,String jname){
		Map<String,Object> condition=new HashMap<String,Object>();
		condition.put("jname", jname);
		condition.put("name", name);
		String fileName = "矫正期满登记文件";
		LinkedList<Map<String, Object>> projects = expireService.getAllExpires(condition);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		projects.add(0, map);
		String columnNames[] = { "编号", "矫正单位", "姓名", "个人小结", "解矫意见", "解矫原因", "备注" ,"期满合议表","期满鉴定表","解矫日期"};
		String keys[] = { "id", "jname", "name", "selfevaluation", "opintion", "reason", "remarks", "mergeOption", "expertiseReport", "expireDate" };
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(projects, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		try {
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			try {
				throw e;
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			if (bis != null)
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		return null;
	}
	/**
	 * 矫正人下拉框改变时查询单条矫正人员信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/enterDate")
	public Map<String,Object> getPerson(Integer id){ 
		logger.debug(id);
		CorrectedPerson person = new CorrectedPerson();
		person.setId(id);
		Map<String,Object> map = stateChangeService.getPersonById(person);
		logger.debug("查询单条矫正人员信息!");
		return map;
	}
}
